#include "broad.hpp"
#include "eiennet.hpp"
#include "winux.hpp"
#include "user/user.hpp"
#include "logger.hpp"

using namespace eiennet;
using namespace std;
using namespace winux;

Broad::~Broad()
{
    clearUser();
}

bool Broad::hasUser(uint uid)
{
    // userList.lock();
    for (auto user : userList)
    {
        if (user->uid == uid)
        {
            return true;
        }
    }
    // userList.unlock();
    return false;
}

void Broad::addUser(User *user)
{
    if (user == nullptr)
    {
        WARN("[func] Broad::addUser(User *user) user is nullptr");
    }
    else
    {
        TRACE("[func] Broad::addUser(User *user) user:{0}", user->getInfo().json());
    }
    // userList.push(user);
    userList.push_back(user);
}
User *Broad::getUser(uint uid)
{
    // userList.lock();
    for (auto user : userList)
    {
        if (user->uid == uid)
        {
            return user;
        }
    }
    // userList.unlock();

    return nullptr;
}
void Broad::delUser(uint uid)
{
    TRACE("Broad::delUser(uint uid) {0}", uid);
    // userList.lock();
    // for (auto user : userList)
    // {
    //     if (user->uid == uid)
    //     {
    //         userList.remove(user);
    //         break;
    //     }
    // }
    // userList.unlock();

    for(auto iter = userList.begin();iter != userList.end();iter++){
        if( (*iter)->uid == uid ) {
            userList.erase( iter );
            break;
        }
    }
}
void Broad::clearUser()
{
    TRACE("[func] Broad::clearUser()");
    userList.clear();
}
void Broad::broadcast(Message *msg, uint exceptUid)
{
    TRACE("[func] Broad::broadcast(Message *msg, uint exceptUid) {0}, {1}", msg->json(), exceptUid);
    TRACE(" | ")
    TRACE(" |- userList.size():{0}", userList.size());
    TRACE(" | ")
    for (auto user : userList)
    {
        TRACE(" |- user: uid:{0} name:{1}", user->uid, user->name );
        if (user->uid == exceptUid)
        {
            continue;
        }
        user->emit(msg);
    }
}